//app.js
App({
  /**
   * 小程序初始化
   */
  async onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync("logs") || [];
    logs.unshift(Date.now());
    wx.setStorageSync("logs", logs);
    // 微信授权登录
    try {
      const loginRes = await wx.login();
      if (loginRes.code) {
        const res = await this.http("wechat/login", "GET", {
          code: loginRes.code,
        });
        // 保存后端返回的数据
        this.globalData.openid = res.data.openid;
        this.globalData.session_key = res.data.session_key;
        // 保存用户信息
        this.getUserInfo();
        if (res.data.mobile) {
          this.globalData.mobile = res.data.mobile;
        }
        // openid 获取完成后，执行回调
        if (this.openidReadyCallback) {
          this.openidReadyCallback(res.data.openid);
        }
      }
    } catch (err) {
      wx.showToast({
        title: "登录失败",
        icon: "none",
      });
      console.error("登录失败", err);
    }
  },

  getUserInfo() {
    // 获取用户信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting["scope.userInfo"]) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: (res) => {
              // 后端保存用户信息
              this.http("wechat/saveUserInfo", "post", res.userInfo).then(
                (res) => {
                  this.globalData.userInfo = res.data;
                }
              );
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res);
              }
            },
          });
        }
      },
    });
  },
  /**
   * 退出登录，清理本地和全局数据
   */
  loginOut() {
    wx.removeStorageSync("token");
    wx.removeStorageSync("userInfo");
    this.globalData.userInfo = null;
  },

  /**
   * 封装http请求
   * @param {string} url 接口地址
   * @param {string} method 请求方法
   * @param {object} data 请求数据
   * @param {boolean} showLoading 是否显示加载
   */
  http(url, method = "GET", data = {}, showLoading = true) {
    const apiUrl = this.globalData.apiUrl;
    const currency = {
      openid: this.globalData.openid,
    };
    if (showLoading) {
      if (this.globalData.loadingCount === 0) {
        wx.showLoading({
          title: "loading...",
        });
      }
      this.globalData.loadingCount++;
    }
    return new Promise((resolve, reject) => {
      wx.request({
        url: apiUrl + url,
        header: {
          "app-key": "0196f6a4-f9cf-77fd-9b03-44d3054a295f",
        },
        method,
        data: Object.assign(currency, data),
        timeout: 5000,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            wx.showToast({
              title: "请求失败!",
              icon: "none",
            });
            reject(new Error("Request failed"));
          }
        },
        fail: (err) => {
          wx.showToast({
            title: err.errMsg && err.errMsg.includes("timeout") ?
              "请求超时" : "网络错误",
            icon: "none",
          });
          reject(err);
        },
        complete: (res) => {
          if (showLoading) {
            this.globalData.loadingCount--;
            if (this.globalData.loadingCount <= 0) {
              this.globalData.loadingCount = 0;
              wx.hideLoading();
            }
          }
          console.log(url + "请求成功!");
          console.log(res);
        },
      });
    });
  },

  /**
   * 全局数据
   */
  globalData: {
    userInfo: null,
    mobile: null,
    openid: null,
    imgUrl: "https://tenghao365-qizhi.oss-cn-shanghai.aliyuncs.com/",
    apiUrl: "https://qz.tenghao365.com/prod-api/business/",
    // apiUrl: "https://139.196.97.200/prod-api/business/",
    // apiUrl: "http://127.0.0.1:9401/", //本地测试（打开官方开发工具设置不校验域名）
    loadingCount: 0, // 当前请求数
  },
});